package org.lc.platform.boot.util;

import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.lc.platform.base.constant.AuthConstant;
import org.lc.platform.base.domain.JwtUser;
import org.lc.platform.boot.common.task.ThreadLocalRequestHeaderContext;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Slf4j
public class LcAuthUtils {

    /**
     * 获取用户信息
     *
     * @return LcUser
     */
    public static JwtUser getCurrentUser() {

        HttpServletRequest request = LcWebUtils.getRequest();
        String user;

        if (null != request && !StrUtil.isEmpty(request.getHeader(AuthConstant.HEADER_USER)))
        {
            user = request.getHeader(AuthConstant.HEADER_USER);
        }
        else {
            //当request为null时，尝试从异步线程池的上下文变量中去取
            user = LcAuthUtils.getThreadPoolContextValue();
        }

        if (StrUtil.isEmpty(user))
        {
            return null;
        }

        String userStr = URLDecoder.decode(user, StandardCharsets.UTF_8);
        return JSONUtil.toBean(userStr, JwtUser.class);

    }

    private static String getThreadPoolContextValue(){
        Map<String, String> headers = ThreadLocalRequestHeaderContext.get();
        if (null != headers)
        {
            // CaseInsensitiveMap不区分大小写
            Map<String, String> headersMap = new CaseInsensitiveMap<>(headers);
            // request 的header大小写不敏感，在转换时全部转成了小写
            return headersMap.get(AuthConstant.HEADER_USER);
        }
        return null;
    }
}
